// filePath：fengchao/src/main/java/com/cdvtc/fengchao/Servlet/CartManager.java
package com.cdvtc.fengchao.Servlet;

import com.cdvtc.fengchao.model.CartItem;
import com.cdvtc.fengchao.model.Product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CartManager {
    private static CartManager instance;
    private List<CartItem> cartItems = new ArrayList<>();

    private CartManager() {}

    public static synchronized CartManager getInstance() {
        if (instance == null) {
            instance = new CartManager();
        }
        return instance;
    }

    public void addToCart(Product product, int quantity) {
        if (product == null) {
            System.out.println("商品为空，无法加入购物车！");
            return;
        }
        if (quantity <= 0) {
            System.out.println("商品数量必须大于0，无法加入购物车！");
            return;
        }
        if (product.getStock() < quantity) {
            System.out.println("商品库存不足，无法加入购物车！");
            return;
        }
        for (CartItem item : cartItems) {
            if (item.getProduct().getId() == product.getId()) {
                if (item.getQuantity() + quantity > product.getStock()) {
                    System.out.println("商品库存不足，无法加入购物车！");
                    return;
                }
                item.setQuantity(item.getQuantity() + quantity);
                return;
            }
        }
        // 如果商品不存在，添加新的购物车项
        try {
            BigDecimal price = new BigDecimal(product.getPrice().replaceAll("[^0-9.]", ""));
            CartItem newItem = new CartItem(product.getId(), product.getName(), price, quantity, product);
            cartItems.add(newItem);
        } catch (NumberFormatException e) {
            System.out.println("商品价格格式错误，无法加入购物车！");
        }
    }

    public List<CartItem> getCartItems() {
        return cartItems;
    }

    public void removeFromCart(int productId) {
        cartItems.removeIf(item -> item.getProduct().getId() == productId);
    }

    public void updateQuantity(int productId, int quantity) {
        if (quantity <= 0) {
            removeFromCart(productId);
            return;
        }
        for (CartItem item : cartItems) {
            if (item.getProduct().getId() == productId) {
                if (quantity > item.getProduct().getStock()) {
                    System.out.println("商品库存不足，无法更新数量！");
                    return;
                }
                item.setQuantity(quantity);
                return;
            }
        }
    }

    public BigDecimal getTotalAmount() {
        BigDecimal total = BigDecimal.ZERO;
        for (CartItem item : cartItems) {
            total = total.add(item.getSubtotal());
        }
        return total;
    }
}
